﻿using System;
using System.Composition;
using Unread.Notifications.Models;
using Unread.Notifications.Services.Interfaces;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;

namespace Unread.Notifications.Services
{
    [Export(typeof(ITileUpdater))]
    internal class TileUpdater : ITileUpdater
    {
        public void Update(TileUpdateRequest request)
        {
            if (request == null) throw new ArgumentNullException("request");

            var notification = CreateUnreadItemsTileNotification(request.LargeText, request.RegularText, request.Delay);

            TileUpdateManager.CreateTileUpdaterForApplication().AddToSchedule(notification);
        }

        private ScheduledTileNotification CreateUnreadItemsTileNotification(string largeText, string regularText, TimeSpan delay)
        {
            var tile = CreateTileSquareBlock(largeText, regularText);
            var deliveryTime = DateTime.Now.Add(delay);

            return new ScheduledTileNotification(tile, deliveryTime) 
            { 
                Id = Guid.NewGuid().ToString().Substring(0, 15)
            };
        }

        private XmlDocument CreateTileSquareBlock(string largeText, string regularText)
        {
            var tileContent = string.Format(@"
                <tile>
                    <visual>
                        <binding template='TileSquareBlock'>
                            <text id='1'>{0}</text>
                            <text id='2'>{1}</text>
                        </binding>
                    </visual>
                </tile>", largeText, regularText);


            var tile = new XmlDocument();
            tile.LoadXml(tileContent);

            return tile;
        }
    }
}